#!/usr/bin/env python

from wx import Dialog, Panel, BoxSizer, StaticBox, StaticBoxSizer, TextCtrl, ListBox, Button, StaticText
from wx import VERTICAL, HORIZONTAL, LB_EXTENDED, EVT_LISTBOX_DCLICK, EVT_KEY_UP, LEFT, ALL, EXPAND, ALIGN_CENTER, TOP, BOTTOM, RIGHT, EVT_BUTTON
from ConfigParser import RawConfigParser
from time import sleep


class LoginDialog(Dialog):

  def __init__(self, parent, title, labelText, players, lastLoadedPlayer, br, sleepSeconds):
    super(LoginDialog, self).__init__(parent=parent,
        title=title, size=(250, 500))

    self.sleepSeconds = sleepSeconds
    self.br = br
    self.lastLoadedPlayer = lastLoadedPlayer or ''
    self.players = players
    self.playersList = [ (p, players[p]['password'], players[p]['proxy'], players[p]['schedule'], players[p]['numComplete']) for p in players if p]

    panel = Panel(self)
    vbox = BoxSizer(VERTICAL)

    sb = StaticBox(panel, label='Login')
    sbs = StaticBoxSizer(sb, orient=VERTICAL)
    self.userbox = TextCtrl(panel, -1, size=(200,25), value=self.lastLoadedPlayer)
    pw = ''
    proxy = ''
    schedule = ''
    if self.lastLoadedPlayer in self.players:
      pw = self.players[self.lastLoadedPlayer]['password']
      schedule = self.players[self.lastLoadedPlayer]['schedule']
      proxy = self.players[self.lastLoadedPlayer]['proxy']
    self.passbox = TextCtrl(panel, 1, size=(200,25), value=pw)
    self.proxybox = TextCtrl(panel, 1, size=(200,25), value=proxy)
    self.schedulebox = TextCtrl(panel, 1, size=(200,25), value=schedule)
    self.playersListBox = ListBox(panel, -1, style=LB_EXTENDED, size=(200,170),
                        choices= ['%s (%s)' % (p,numComplete) for p,pw,pr,schedule,numComplete in self.playersList if p])

    self.playersListBox.Bind(EVT_LISTBOX_DCLICK, self.updateToSelectedPlayer)

    self.userbox.Bind(EVT_KEY_UP, self.doOkIfEnter)
    self.passbox.Bind(EVT_KEY_UP, self.doOkIfEnter)
    self.proxybox.Bind(EVT_KEY_UP, self.doOkIfEnter)
    self.schedulebox.Bind(EVT_KEY_UP, self.doOkIfEnter)
    self.statusLabel = StaticText(panel, label=labelText)
    hbox1 = BoxSizer(VERTICAL)
    hbox1.Add(self.playersListBox, flag=LEFT, border=5)
    hbox1.Add(StaticBox(panel, label='Username'))
    hbox1.Add(self.userbox, flag=LEFT, border=5) 
    hbox1.Add(StaticBox(panel, label='Password'))
    hbox1.Add(self.passbox, flag=LEFT, border=5)
    hbox1.Add(StaticBox(panel, label='Proxy'))
    hbox1.Add(self.proxybox, flag=LEFT, border=5)
    hbox1.Add(StaticBox(panel, label='Scheduled for'))
    hbox1.Add(self.schedulebox, flag=LEFT, border=5)
    hbox1.Add(self.statusLabel)
    sbs.Add(hbox1)

    panel.SetSizer(sbs)

    hbox2 = BoxSizer(HORIZONTAL)
    okButton = Button(self, label='Ok')
    closeButton = Button(self, label='Close')
    closeButton.Bind(EVT_BUTTON, self.OnClose)
    hbox2.Add(okButton)
    hbox2.Add(closeButton, flag=LEFT, border=5)

    vbox.Add(panel, proportion=1, flag=ALL|EXPAND, border=5)
    vbox.Add(hbox2, flag= ALIGN_CENTER|TOP|BOTTOM, border=10)

    self.SetSizer(vbox)

    okButton.Bind(EVT_BUTTON, self.OnOK)
    self.userbox.SetFocus()
    self.username = None
    self.password = None
    self.proxy = None
    self.schedule = None
    self.authenticated = False

  def OnClose(self, e):
    self.Close()


  def updateToSelectedPlayer(self, e):
    if len(self.playersListBox.GetSelections() )==1:
      index = self.playersListBox.GetSelections()[0]
      newPlayer = self.playersList[index]
      self.userbox.SetValue(newPlayer[0])
      self.passbox.SetValue(newPlayer[1])
      self.proxybox.SetValue(newPlayer[2])
      self.schedulebox.SetValue(newPlayer[3])
    else:
      print 'too little or too many selected'


  def doOkIfEnter(self, event):
    keycode = event.GetKeyCode()
    if keycode == 13:
      self.OnOK(event)


  def OnOK(self, event):
    username = self.userbox.GetValue()
    password = self.passbox.GetValue()
    proxy    = self.proxybox.GetValue()
    schedule = self.schedulebox.GetValue()
    self.statusLabel.SetLabel('Attempting Login.')
    self.statusLabel.Update()
    sleep(.1)
    self.statusLabel.Update()
    if self.username!='' and self.password!='':
      response = self.br.doLogin(username, password, proxy, self.sleepSeconds)
      if response == 'Successful login':
        self.username = username
        self.password = password
        self.proxy = proxy
        self.schedule = schedule
        self.statusLabel.SetLabel('Logged in Succesfully!')
        self.Close()
      else:
        self.statusLabel.SetLabel('Login Failed')
        self.password = 'Failed Login'
    else:
      self.statusLabel.SetLabel('BAD username/password info')


  def GetResult(self):
    if self.username == None:
      return (None, None)

    config = RawConfigParser()
    config.read('settings.cfg')
    if self.username not in config.sections():
      config.add_section(str(self.username))
    config.set(self.username, 'password', self.password)
    config.set(self.username, 'proxy', self.proxy)
    config.set(self.username, 'schedule', self.schedule)
    config.set('def','lastloadedplayer',self.username)
    with open('settings.cfg','wb') as f:
      config.write(f)
    return (self.username, self.password)

